<template>
    <div class="edu-page-warp">
        <div class="edu-page-title">
			上传文件列表
		</div>
        <el-card shadow="never" body-style="padding: 24px;">
            <el-row :gutter="20">
            <el-col :span="12">
            <span class="upload-span">考生名单</span>
            <div class="upload-box">
                <el-upload
                    class="upload-demo"
                    accept=".xls,.xlsx"
                    :on-preview="handleExaminationPreview"
                    :before-remove="beforeExaminationRemove"
                    :on-remove="handleExaminationRemove"
                    :http-request="examinationUpload"
                    :on-exceed="uploadFileExceed"
                    :on-success="uploadFileSuccess"
                    :on-error="uploadFileFailure"
                    action=""
                    :limit="maxFileCount"
                    :file-list="examinationNames">
                    <el-button size="small">点击上传</el-button>
                    <div slot="tip" class="el-upload__tip">格式：请按照考生名单模板填写并上传文件</div>
                </el-upload>
            </div>
            </el-col>
            <el-col :span="12">
            <span class="upload-span">考生成绩</span>
            <div class="upload-box">
                <el-upload
                    class="upload-demo"
                    accept=".xls,.xlsx"
                    :on-preview="handleScorePreview"
                    :before-remove="beforeScoreRemove"
                    :on-remove="handleScoreRemove"
                    :http-request="scoreUpload"
                    :on-exceed="uploadFileExceed"
                    :on-success="uploadFileSuccess"
                    :on-error="uploadFileFailure"
                    action=""
                    :limit="maxFileCount"
                    :file-list="scoreNames">
                    <el-button size="small">点击上传</el-button>
                    <div slot="tip" class="el-upload__tip">格式：请按照考生成绩模板填写并上传文件。</div>
                </el-upload>
                </div>
            </el-col>
        </el-row>
        </el-card>
        <el-dialog :title="dialogExaminationTitle" :visible.sync="dialogExaminationVisible">
            <el-table :data="examinationNamesList">
                <el-table-column property="studentId" label="学号" width="100"></el-table-column>
                <el-table-column property="name" label="姓名" width="100"></el-table-column>
                <el-table-column property="gender" label="性别" width="50">
                    <template slot-scope="scope">
						<span>{{ scope.row.gender | sex}}</span>
					</template>
                </el-table-column>
                <el-table-column property="level" label="分级"></el-table-column>
                <el-table-column property="examTime" label="考试时间" width="200"></el-table-column>
                <el-table-column property="examPos" label="考试教室"></el-table-column>
                <el-table-column property="notice" label="考生须知" width="300"></el-table-column>
            </el-table>
            <div class="edu-pagination">
                <div class="float-left">
                    <span class="edu-total">Total: {{ queryExamItem.total }}</span>
                </div>
                <div class="float-right">
                <el-pagination
                    @size-change="handleExamSizeChange"
                    @current-change="handleExamCurrentChange"
                    :current-page="queryExamItem.pageNum_"
                    :page-sizes="[20,50,100,500,1000]"
                    :page-size="10"
                    layout=" sizes, prev, pager, next, jumper"
                    :total="queryExamItem.total">
                </el-pagination>
                </div>
            </div>
        </el-dialog>
        <el-dialog :title="dialogScoreTitle" :visible.sync="dialogScoreVisible">
            <el-table :data="scoreNamesList">
                <el-table-column property="studentId" label="学号"></el-table-column>
                <el-table-column property="name" label="姓名"></el-table-column>
                <el-table-column property="course" label="考试科目"></el-table-column>
                <el-table-column property="examScore" label="考试成绩"></el-table-column>
                <el-table-column property="courseSelectSuggest" label="建议课程"></el-table-column>
            </el-table>
            <div class="edu-pagination">
                <div class="float-left">
                    <span class="edu-total">Total: {{ queryScoreItem.total }}</span>
                </div>
                <div class="float-right">
                <el-pagination
                    @size-change="handleScoreSizeChange"
                    @current-change="handleScoreCurrentChange"
                    :current-page="queryScoreItem.pageNum_"
                    :page-sizes="[20,50, 100,500,1000]"
                    :page-size="20"
                    layout=" sizes, prev, pager, next, jumper"
                    :total="queryScoreItem.total">
                </el-pagination>
                </div>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import {
  getExaminationNames,
  getScoreNames,
  updateExamination,
  updateScore,
  getExaminationList,
  getScoreList,
  delExamList,
  delScoreList
} from "common/src/api/welcomeService/examinationTask";
import filters from "common/src/filters";

export default {
  name: "UploadFiles",
  data() {
    return {
      id: this.$route.params.taskId,
      dialogExaminationVisible: false,
      dialogExaminationTitle: "",
      dialogScoreVisible: false,
      dialogScoreTitle: "",
      queryScoreItem: {
        total: 0,
        templateId: this.$route.params.taskId,
        importFileName: "",
        pageNum_: 1,
        pageSize_: 20
      },
      queryExamItem: {
        total: 0,
        templateId: this.$route.params.taskId,
        importFileName: "",
        pageNum_: 1,
        pageSize_: 20
      },
      examinationNames: [],
      maxFileCount: 5,
      scoreNames: [],
      examinationNamesList: [],
      scoreNamesList: []
    };
  },
  filters: {
    sex(val) {
      return filters.sexFilter(val);
    }
  },
  methods: {
    examinationUpload(file) {
      console.log(file);
      if (!file.file.name.endsWith(".xlsx") && !file.file.name.endsWith(".xls")){
        return Promise.reject({
            code: 200,
            msg: "文件格式错误！"
        })
      }

      let fd = new FormData();
      fd.append("file", file.file);
      fd.append("templateId", this.id);
      return updateExamination(fd).then(
          res => {
              if (res.code == 200) {
                return Promise.resolve(res);
              } else {
                return Promise.reject(res);
              }
          },
          err => {
            return Promise.reject(err);
          }
        );
    },
    uploadFileExceed() {
        this.$message({
            message: `最多只能上传${this.maxFileCount}个文件`,
            type: "info"
        });
    },
    scoreUpload(file) {
      if (!file.file.name.endsWith(".xlsx") && !file.file.name.endsWith(".xls")){
        return Promise.reject({
            code: 200,
            msg: "文件格式错误！"
        })
      }

      let fd = new FormData();
      fd.append("file", file.file);
      fd.append("templateId", this.id);
      return updateScore(fd).then(
          res => {
              if (res.code == 200) {
                return Promise.resolve(res);
              } else {
                return Promise.reject(res);
              }
          },
          err => {
            return Promise.reject(err);
          }
        );
    },
    uploadFileSuccess(response, file, fileList){
        let isSuccess = (response.code == 200);
        this.$message({
            type: isSuccess ? "success":"error",
            message: response.msg
        });
    },
    uploadFileFailure(err, file, fileList){
        this.$message({
            type: "error",
            message: err.msg
        });
    },
    handleScorePreview(file) {
      this.dialogScoreVisible = true;
      this.queryScoreItem.importFileName = file.name;
      this.dialogScoreTitle = file.name;
      this.initScorePage(this.queryScoreItem)
    },
    handleExaminationPreview(file) {
      this.dialogExaminationVisible = true;
      this.queryExamItem.importFileName = file.name;
      this.dialogExaminationTitle = file.name;
      this.initExamPage(this.queryExamItem);
    },
    beforeExaminationRemove(){
        return this.$confirm("您确定要删除考试名单吗?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
        });
    },
    handleExaminationRemove(file, fileList) {
        let obj = {}
        obj.templateId = file.templateId
        obj.importFileName = file.name
        delExamList(obj)
            .then(res => {
                if (res.code == 200) {
                    this.$message({
                        message: "删除成功",
                        type: "success"
                    });
                } else throw res.msg;
            })
            .catch(err=>{
                this.$message({
                    message: "删除失败",
                    type: "error"
                });
            });
    },
    beforeScoreRemove(file) {
        return this.$confirm("您确定要删除考试成绩吗?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
        });
    },
    handleScoreRemove(file, fileList) {
        let obj = {}
        obj.templateId = file.templateId
        obj.importFileName = file.name
        delScoreList(obj)
            .then(res => {
                if (res.code == 200) {
                    this.$message({
                        message: "删除成功",
                        type: "success"
                    });
                } else throw res.msg;
            }).catch(err=>{
                this.$message({
                    message: "删除失败",
                    type: "error"
                });
            });
    },
    handleExamSizeChange(pageSize) {
        this.queryExamItem.pageSize_ = pageSize
        this.initExamPage(this.queryExamItem)
    },
    handleExamCurrentChange(pageNum) {
        this.queryExamItem.pageNum_ = pageNum
        this.initExamPage(this.queryExamItem)
    },
    initExamPage(options = {}) {
      let query = _.omit(options, ["total"]);
      getExaminationList(query).then(res => {
        if (res.data && res.data.list) {
          this.queryExamItem.total = res.data.total;
          this.queryExamItem.pageNum_ = res.data.pageNum;
          this.queryExamItem.pageSize_ = res.data.pageSize;
          this.examinationNamesList = res.data.list;
        }
      });
    },
    handleScoreSizeChange(pageSize) {
        this.queryScoreItem.pageSize_ = pageSize
        this.initScorePage(this.queryScoreItem)
    },
    handleScoreCurrentChange(pageNum) {
        this.queryScoreItem.pageNum_ = pageNum
        this.initScorePage(this.queryScoreItem)
    },
    initScorePage(options = {}) {
      let query = _.omit(options, ["total"]);
      getScoreList(query).then(res => {
        if (res.data && res.data.list) {
          this.queryScoreItem.total = res.data.total;
          this.queryScoreItem.pageNum_ = res.data.pageNum;
          this.queryScoreItem.pageSize_ = res.data.pageSize;
          this.scoreNamesList = res.data.list;
        }
      });
    }
  },
  mounted() {
    let id = this.$route.params.taskId;
    getExaminationNames(id).then(res => {
      if (res && res.data.length > 0) {
        res.data.forEach(ele => {
          let fileObj = {};
          fileObj.name = ele.importFileName;
          fileObj.templateId = ele.templateId;
          fileObj.url = "";
          this.examinationNames.push(fileObj);
        });
      }
    });

    getScoreNames(id).then(res => {
      if (res && res.data.length > 0) {
        res.data.forEach(ele => {
          let fileObj = {};
          fileObj.name = ele.importFileName;
          fileObj.templateId = ele.templateId;
          fileObj.url = "";
          this.scoreNames.push(fileObj);
        });
      }
    });
  }
};
</script>
<style lang="scss" scoped>
.upload-span {
  display: block;
  float: left;
  line-height: 34px;
  margin-right: 10px;
}
.upload-box {
  float: left;
}
</style>

